
const myDb = require('../../../libs/mydb')

const baseModel = require('../../common/models/BaseModel')

const myCrypto = require('../../../utiles/mycrypto')

const mytoken = require('../../../libs/mytoken')
const getYMDHMS = require('../../../utiles/time')
const { qcobj } = require('../../../conf/index')


// 短信
const QcloudSms = require('qcloudsms_js');
const { md5 } = require('../../../utiles/mycrypto')
const mydb = require('../../../libs/mydb')
const qcloudsms = QcloudSms(qcobj.appid, qcobj.appkey);

let params = [];

module.exports = {
    /**
     * 
     * @param {*} req 
     * @param {*} res 
     */
    // 用户账号验证
    check_user: async function (req, res) {
        console.log(params);
        let { uname, upassword } = req.body;

        if (baseModel.check_empty(uname)) {
            res.send({
                code: 400,
                msg: 'Data is not empty'
            })
        } else {
            await myDb.singleSearch('ac_user', 'u_id,u_password', ` WHERE u_name='${uname}'`)
                .then(
                    result => {
                        if (result.length == 0) {
                            res.send({
                                code: 401,
                                msg: 'Uname is not Find'

                            })
                        } else {
                            if (result[0].u_password != myCrypto.md5(upassword)) {
                                res.send({
                                    code: 402,
                                    msg: 'Password error'

                                })

                            } else {

                                let token = mytoken.add({
                                    uname,
                                    uid: result[0].u_id
                                })
                                myDb.modify('ac_user', {
                                    'u_token': token,
                                    'u_last_log': getYMDHMS(Date.now())
                                }, ` WHERE u_name='${uname}'`)
                                    .then(
                                        result => {
                                            if (result) {
                                                res.setHeader('User-Token', token)
                                                res.send({
                                                    code: 200,
                                                    msg: 'ok',
                                                    token

                                                })

                                            }
                                        }
                                    )

                            }

                        }
                    }
                )

        }


    },


    /**
     * 用户注册
     * @param {*} req 
     * @param {*} res 
     */
    user_logup: async function (req, res) {
        if (params.length == 0) {
            res.send({
                code: 400,
                msg: 'Verify not sent'
            })
        } else {
            if (params.join() != req.body.params) {
                res.send({
                    code: 401,
                    msg: 'Verification code error'
                })
            } else {
                if (baseModel.check_empty(req.body.u_name)) {
                    res.send({
                        code: 402,
                        msg: 'Data is not empty'
                    })
                } else {
                    await myDb.singleSearch('ac_user', 'u_id', ` WHERE u_name='${req.body.u_name}'`)
                        .then(
                            async result => {
                                if (result.length != 0) {
                                    console.log(result);
                                    res.send({
                                        code: 403,
                                        msg: 'User name exists with'
                                    })
                                } else {
                                    await myDb.add('ac_user', {
                                        'u_name': req.body.u_name,
                                        'u_password': md5(req.body.u_password),
                                        'u_tele': req.body.u_tele,
                                        'u_reg_time': req.body.u_reg_time
                                    }, '')
                                        .then(
                                            async result => {
                                                if (result) {
                                                    await myDb.singleSearch('ac_user', 'u_id', ` WHERE u_name='${req.body.u_name}'`)
                                                        .then(
                                                            result => {
                                                                if (result) {
                                                                    mydb.add('ac_user_info', {
                                                                        'uid': result[0].u_id,
                                                                        'u_nick': req.body.u_name,
                                                                        'u_headers': '1.jpg'
                                                                    }, '')
                                                                        .then(
                                                                            result => {
                                                                                if (result) {
                                                                                    params = []
                                                                                    res.send({
                                                                                        code: 200,
                                                                                        msg: 'ok'
                                                                                    })
                                                                                } else {
                                                                                    res.send({
                                                                                        code: 405,
                                                                                        msg: 'Login has failed'
                                                                                    })
                                                                                }
                                                                            }
                                                                        )
                                                                }
                                                            }
                                                        )
                                                } else {
                                                    res.send({
                                                        code: 404,
                                                        msg: 'Login has failed'
                                                    })
                                                }
                                            }
                                        )
                                }
                            }
                        )
                }
            }
        }
    },
    /**
     * 用户头像更改
     * @param {*} req 
     * @param {*} res 
     */
    change_header: function (req, res) {
        myDb.modify('ac_user_info', { 'u_headers': req.files.file.name }, ` WHERE uid=${req.body.id}`)
            .then(
                result => {
                    if (result) {
                        res.send({
                            code: 200,
                            msg: 'ok',
                            url: req.files.file.name
                        })
                    } else {
                        res.send({
                            code: 400,
                            msg: 'Replacement failed'
                        })
                    }
                }
            )
    },

    /**
     * 发送验证码
     * @param {*} req 
     * @param {*} res 
     */
    phone_verification: function (req, res) {
        console.log(req.body);
        console.log(req.body.phone);
        if (req.body.phone) {
            let phoneNumber = req.body.phone
            let ssender = qcloudsms.SmsSingleSender();
            params = [qcobj.random];
            ssender.sendWithParam("86", phoneNumber, qcobj.templateId,
                params, qcobj.smsSign, "", "", (err, result, resData) => {
                    if (err) {
                        res.send({
                            code: 400,
                            msg: 'Fail in send'
                        })
                    } else {
                        // console.log("request data: ", result.req);
                        // console.log("response data: ", resData);
                        res.send({
                            code: 200,
                            msg: 'OK'
                        })
                    }
                });
    
        } else {
            res.send({
                code:401,
                msg: 'No mobile number submitted'
            })
        }

    },

    /**
     * 忘记密码手机验证重置密码
     * @param {*} req 
     * @param {*} res 
     */
    forget_password: function (req, res) {
        if (params.length == 0) {
            res.send({
                code: 400,
                msg: 'Verify not sent'
            })
        } else {
            if (params.join() != req.body.params) {
                res.send({
                    code: 401,
                    msg: 'Verification code error'
                })
            } else {
                myDb.singleSearch('ac_user', 'u_tele,u_id', ` WHERE u_name = '${req.body.u_name}'`)
                    .then(
                        async result => {
                            if (result) {
                                console.log(result);
                                console.log(666);
                                if(result[0].u_tele == req.body.u_tele) {

                                    await myDb.modify('ac_user', { 'u_password': md5(req.body.u_password) }, ` WHERE u_id='${result[0].u_id}'`)
                                        .then(
                                            result => {
                                                if (result) {
                                                    params = []
                                                    res.send({
                                                        code: 200,
                                                        msg: 'ok'
                                                    })
                                                } else {
                                                    res.send({
                                                        code:404,
                                                        msg: 'Password modification failed'
                                                    })
                                                }
                                            }
                                        )

                                }else {
                                    res.send({
                                        code: 403,
                                        msg: 'Inconsistent mobile phone number'
                                    })
                                }
                            } else {
                                res.send({
                                    code:402,
                                    msg: 'There is no such user'
                                })
                            }
                        }
                    )
            }
        }
        
    }

}

